import fetch from "../../utils/fetch";
const globalData = getApp().globalData;
const userId = globalData.userInfo.id;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: '早餐',
    recordDate: '', // 记录的日期
    activeIndex: 0,
    selectedFoodcate: '常用',
    foodcateList: [{
        foodcate: "常用",
        // foodList: []
      },
      {
        foodcate: "收藏",
        // foodList: []
      }
    ],
    foodList: [
      // {
      //   id: "7shi biantaorenpian",
      //   name: "7式 扁桃仁片",
      //   img: "http://image.hpcn21.com/upfiles/food/201601/sa20160110092748.jpg",
      //   heat_cal: "646.03 千卡"
      // },
      // {
      //   id: "baiguo（xian）",
      //   name: "白果（鲜）",
      //   img: "http://image.hpcn21.com/upfiles/food/201601/sa20160129184825.jpg",
      //   heat_cal: "0.00 千卡"
      // },
      // {
      //   id: "baiguogan",
      //   name: "白果(干)",
      //   img: "http://image.hpcn21.com/upfiles/food/201410/1454/sa2014091411114523.jpg",
      //   heat_cal: "355.00 千卡"
      // },
      // {
      //   id: "baiziren",
      //   name: "柏子仁",
      //   img: "http://image.hpcn21.com/upfiles/food/201410/4007/sa201412141975757.jpg",
      //   heat_cal: "0.00 千卡"
      // },
      // {
      //   id: "bigenguo",
      //   name: "碧根果",
      //   img: "http://image.hpcn21.com/upfiles/food/201410/1491/sa201409151535422.jpg",
      //   heat_cal: "670.00 千卡"
      // },
      // {
      //   id: "boluomizi",
      //   name: "菠萝蜜子",
      //   img: "http://image.hpcn21.com/upfiles/food/201410/1469/sa201409141643049.jpg",
      //   heat_cal: "165.00 千卡"
      // },
    ],
    show: false, // 食物添加弹出层
    recordShow: false, // 所有饮食记录弹出层
    gramCurrentNumber: 100,
    gram: 100,
    tempGramCurrentNumber: 100, // 保存所有popup的初始值
    unitHeat: 0, // 当前选中的食物单位热量
    foodHeat: 0, // 当前选中的食物总热量
    selectedFood: {}, // 选中的食物
    foodRecord: [
      //   {
      //   foodId: "adgainai",
      //   heat: 60.5,
      //   img: "http://image.hpcn21.com/upfiles/food/201410/4181/sa20141224104704.jpg",
      //   name: "AD钙奶",
      //   num: 110,
      //   recordDate: "2024-01-27",
      //   time: "早餐",
      //   userId: 22,
      // }
    ] // 添加的食物
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      time: options.recordTime,
      recordDate: options.recordDate
    });
    this.initFoodCate();
  },
  getOftenAndCollect() {
    const foodcateList = this.data.foodcateList;
    fetch(`/food/oftenAndCollect?userId=${userId}`).then(res => {
      const {
        oftenUseArr,
        collectArr
      } = res.data;
      const filterOftenArr = oftenUseArr.map(item => {
        return item.food
      });
      const filterCollectArr = collectArr.map(item => {
        return item.food;
      });
      foodcateList[0].foodList = filterOftenArr;
      foodcateList[1].foodList = filterCollectArr;
      this.setData({
        foodcateList,
        foodList: this.data.selectedFoodcate == '常用' ? filterOftenArr : filterCollectArr
      })
    })
  },
  initFoodCate() {
    const foodcateList = this.data.foodcateList;
    fetch('/food/').then(res => {
      const newFoodcateList = foodcateList.concat(res.data.foodcate);
      this.setData({
        foodcateList: newFoodcateList,
      })
      this.getOftenAndCollect(userId);
      this.setData({
        foodList: this.data.foodcateList[0].foodList
      })
    })

  },
  // 选择食物分类
  tapCategory(e) {
    const index = e.currentTarget.dataset.index;
    const name = this.data.foodcateList[index].foodcate
    this.setData({
      activeIndex: index,
      selectedFoodcate: name
    })
    this.getFoodList(name, index);
  },
  getFoodList(name, index) {
    // 如果是常用和收藏
    if (name == '常用' || name == '收藏') {
      this.getOftenAndCollect();
    } else {
      this.getFoodcate(name, index);
    }
  },
  getFoodcate(name, index) {
    fetch('/food/foodcate', {
      foodcate: name,
      userId: userId
    }, 'post').then(res => {
      const newFoodList = res.data.food;
      const newFoodcateList = this.data.foodcateList;
      newFoodcateList[index].foodList = newFoodList;
      this.setData({
        foodcateList: newFoodcateList,
        foodList: newFoodList
      })
    })
  },
  showPopup(e) {
    const foodId = e.currentTarget.dataset.foodId;
    const food = this.data.foodList.find(item => item.id === foodId);
    food.carbohydrate = parseFloat(food['碳水化合物(克)']) ? parseFloat(food['碳水化合物(克)']) : 0.0;
    food.protein = parseFloat(food['蛋白质(克)']) ? parseFloat(food['蛋白质(克)']) : 0.0;
    food.fat = parseFloat(food['脂肪(克)']) ? parseFloat(food['脂肪(克)']) : 0.0;
    const unitHeat = parseFloat(food['热量(大卡)']);
    this.setData({
      selectedFood: food,
      unitHeat,
      foodHeat: isNaN(unitHeat) ? 0 : unitHeat,
      gramCurrentNumber: this.data.tempGramCurrentNumber,
      show: true
    });

  },
  closePopup(){
    this.setData({
      show: false
    });
  },
  onClose(e) {
    const foodRecord = e.detail.foodRecord;
    this.setData({
      show: false,
      foodRecord
    });
  },

  closeRecord() {
    this.setData({
      recordShow: false
    })
  },
  showRecord() {
    this.setData({
      recordShow: true
    })
  },
  getCurrentNumbergram(e) { //克数
    let result = e.detail.current;
    const foodHeat = parseFloat(this.data.unitHeat * (result / 100)).toFixed(2);
    this.setData({
      gram: result,
      gramCurrentNumber: result,
      foodHeat
    })
  },
  gotoSearch() {
    wx.navigateTo({
      url: `../search/search?fromId=1&recordDate=${this.data.recordDate}&time=${this.data.time}`,
    })
  },
  gotoDetail(e) {
    const foodId = e.currentTarget.dataset.foodId;
    wx.navigateTo({
      url: `../foodDetail/foodDetail?foodId=${foodId}&recordDate=${this.data.recordDate}&time=${this.data.time}`,
    })
  },
  addFood() {
    const food = {};
    food.time = this.data.time;
    food.num = this.data.gram;
    food.heat = parseFloat(this.data.foodHeat);
    food.userId = userId;
    food.recordDate = this.data.recordDate;
    const {
      id,
      img,
      name,
      carbohydrate,
      protein,
      fat
    } = this.data.selectedFood;
    food.foodId = id;
    food.name = name;
    food.img = img;
    const temp = parseFloat(this.data.gram / 100);
    food.carbohydrate = parseFloat(carbohydrate * temp).toFixed(2);
    food.protein = parseFloat(protein * temp).toFixed(2);
    food.fat = parseFloat(fat * temp).toFixed(2);
    const foodRecord = this.data.foodRecord;
    foodRecord.push(food);
    this.setData({
      foodRecord,
      show: false
    });
  },
  // 删除食物
  deleteFood(e) {
    const i = e.currentTarget.dataset.index;
    const foodRecord = this.data.foodRecord;
    const newRecord = foodRecord.filter((item, index) => index !== i);
    this.setData({
      foodRecord: newRecord
    });
  },
  addRecord() {
    fetch('/foodRecord/add', {
      foodRecord: this.data.foodRecord
    }, 'post').then(res => {
      if (res.code === 200) {
        this.setData({
          show: false
        })
        wx.navigateTo({
          url: `../foodRecord/foodRecord?recordTime=${this.data.time}&recordDate=${this.data.recordDate}`,
        })
      }
    })
  },
  changeCollect(e) {
    const foodId = e.currentTarget.dataset.foodId;
    const isCollect = this.data.selectedFood.isCollect;
    const foodList = this.data.foodList;
    const idx = foodList.findIndex(item => item.id === foodId);
    if (!isCollect) {
      fetch(`/collect?userId=${userId}&id=${foodId}&collectType=food`).then(res => {
        if (res.code === 200) {
          foodList[idx].isCollect = true;
          this.setData({
            'selectedFood.isCollect': !isCollect,
            foodList
          });
        }
      })
    } else {
      fetch(`/collect/uncollect?userId=${userId}&id=${foodId}&collectType=food`).then(res => {
        if (res.code === 200) {
          foodList[idx].isCollect = false;
          this.setData({
            'selectedFood.isCollect': !isCollect,
            foodList
          });
          this.getOftenAndCollect()
        }
      })
    }
  }
})